var express = require('express');
var multer = require('multer');
var router = express.Router();
var uuid = require('uuid');
var fs = require('fs');
var path = require('path');
var appConfig = require('../../config');
var ImageUtil = require('../../utils/utils').ImageUtil;

var upload = multer({ dest: appConfig.upload.temp });

router.post('/upload', upload.single('file'), function(req, res, next) {
	var date  = new Date();
  var year  = date.getFullYear();
  var month = date.getMonth() + 1;
  month     = month < 10 ? '0' + month : month;
  var d     = date.getDate();
  d         = d < 10 ? '0' + d : ('' + d);
  var ext = '';
  console.log(req.file);
  // if (req.file.mimetype === 'image/jpeg' || req.file.mimetype === 'image/jpg') {
  //   ext = '.jpg';
  // } else if (req.file.mimetype === 'image/gif') {
  // 	ext = '.gif';
  // } else if (req.file.mimetype === 'image/png') {
  // 	ext = '.png';
  // } else {
  // 	return res.json({
  // 		state    : 'FAIL',
  // 		url      : 'xx',
  //       title    : req.file.filename,
  //       original : req.file.originalname	
  // 	});	
  // }
  var index = req.file.originalname.lastIndexOf('.') || 0;
  ext = req.file.originalname.substring(index, req.file.originalname.length);
  console.log(ext);
  var oldpath = path.join(appConfig.upload.temp, req.file.filename);
  var filePath = year + month + '/' + d + '/' + uuid.v1() + ext;
  var newPath = path.join(appConfig.upload.path, filePath);

  var fileData = {
    url      : appConfig.upload.rootPath + '/' + filePath,
    title    : req.file.filename,
    original : req.file.originalname,
    success  : false
  };
  ImageUtil.mkdir(path.join(appConfig.upload.path), function(err) {
  	if (err) {
  		return res.json(fileData);
  	}
  	ImageUtil.mkdir(path.join(appConfig.upload.path, year + '' + month), function(err) {
  		if (err) {
  			return res.json(fileData);
  		}
  		ImageUtil.mkdir(path.join(appConfig.upload.path, year + '' + month, d), function(err) {
  			if (err) {
  				return res.json(fileData);
  			}
  			fs.rename(oldpath, newPath, function(err) {
  				if (err) {
  					return res.json(fileData);
  				} else {
  					fileData.success = true;
  					return res.json(fileData);
  				}
  			});
  		})
  	})
  });
});
module.exports = router;